package com.rzico.sbl.ui.report

import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityCommonListBinding
import com.rzico.sbl.model.ManagerContent
import com.rzico.sbl.model.ManagerDivider
import com.rzico.sbl.other.serviceId
import com.rzico.sbl.ui.report.driver.DriverCouponActivity
import com.rzico.sbl.ui.report.driver.DriverStationActivity
import com.rzico.sbl.ui.report.driver.DriverStockActivity
import com.rzico.sbl.ui.report.other.ReportService
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToBuy
import com.rzico.sbl.viewmodel.ReportViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadGrid
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter

class ReportActivity : BaseActivity(R.layout.activity_common_list) {

    private val mBinding by lazy { ActivityCommonListBinding.bind(getRootView()) }

    private val mLimitStatus = MutableLiveData("0")

    override fun getViewModel() = get<ReportViewModel>()

    override fun initData() {
        initTitle(title = "报货系统")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                recycleList.also { layout ->
                    layout.layoutParams = FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT
                    ).apply {
                        setMargins(dp2px(15f), 0, dp2px(15f), 0)
                    }

                    layout.loadGrid(
                        refresh = swipeRefresh,
                        onRefresh = {
                            getViewModel().getCount("0")
                            if (mLimitStatus.value == "1")
                                getViewModel().getCount("1")

                            getViewModel()
                                .delay(time = 1000) {
                                    swipeRefresh.isRefreshing = false
                                    mAdapter.notifyDataSetChanged()
                                }
                        },
                        init = {
                            layoutManager = GridLayoutManager(
                                getIContext(),
                                4
                            ).apply {
                                spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                                    override fun getSpanSize(position: Int): Int = when {
                                        mAdapter.getItem(position) is ManagerContent -> 1
                                        else -> 4
                                    }
                                }
                            }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<ManagerDivider>(R.layout.item_manager_divider) { jector, bean, index ->

                            // 解构声明
                            val (title, _) = bean

                            jector.apply {
                                gone(R.id.divder_edit)
                                text(R.id.divder_title, title)

                                getView<View>(R.id.divder_title)
                                    .isGone = index == mList.size - 1

                                getView<View>(R.id.divder_hint1)
                                    .isGone = index == 0

                                getView<View>(R.id.divder_hint2)
                                    .isGone = index == mList.size - 1

                                getView<View>(R.id.divder_hint3)
                                    .isVisible = index == mList.size - 1
                            }
                        }
                        .register<ManagerContent>(R.layout.item_manager_grid) { jector, bean, _ ->

                            // 解构声明
                            val (title, imageId, _, _, count) = bean

                            jector.apply {
                                text(R.id.manager_hint, title)

                                with<ImageView>(R.id.manager_image) {
                                    if (imageId > 0) it.setImageResource(imageId)
                                }

                                with<BadgeTextView>(R.id.manager_num) {
                                    it.setBadgeCount(count)
                                }

                                getView<View>(R.id.manager_hint).isInvisible = title.isEmpty()
                                getView<View>(R.id.manager_image).isInvisible = title.isEmpty()

                                clicked {
                                    when (title) {
                                        "商品" -> startActivityEx<ReportGoodsActivity>()
                                        "采购单" -> goToBuy()
                                        "订单" -> startActivityEx<ReportOrderActivity>()
                                        "运单" -> startActivityEx<ReportDeliverActivity>("index" to 2)
                                        "水站" -> startActivityEx<ReportWaterShopActivity>()
                                        "出入库" -> startActivityEx<ReportDriverDepotActivity>()
                                        "卡券" -> startActivityEx<ReportCouponActivity>()
                                        "活动区" -> startActivityEx<ReportPromoteActivity>()
                                        "商品统计" -> startActivityEx<ReportTotalActivity>()
                                        "库存统计" -> startActivityEx<DriverStockActivity>()
                                        "代金券统计" -> startActivityEx<DriverCouponActivity>()
                                        "水站统计" -> {
                                            when {
                                                mLimitStatus.value == "1"
                                                        && serviceId in ReportService.MODE_DRIVER ->
                                                    startActivityEx<DriverStationActivity>()
                                                else ->
                                                    startActivityEx<DriverStationActivity>("mode" to "hide")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    override fun initListener() {
        // 采购单数量
        getViewModel()
            .mBuyEvent
            .observe(this) { count ->
                mList.any { it is ManagerContent && it.title == "采购单" }
                    .condition {
                        (mList.find {
                            it is ManagerContent && it.title == "采购单"
                        } as ManagerContent).count = count

                        mAdapter.notifyDataSetChanged()
                    }
            }

        // 订单数量
        getViewModel()
            .mOrderEvent
            .observe(this) { count ->
                mList.any { it is ManagerContent && it.title == "订单" }
                    .condition {
                        (mList.find {
                            it is ManagerContent && it.title == "订单"
                        } as ManagerContent).count = count

                        mAdapter.notifyDataSetChanged()
                    }
            }

        // 运单数量
        getViewModel()
            .mDeliverEvent
            .observe(this) { count ->
                mList.any { it is ManagerContent && it.title == "运单" }
                    .condition {
                        (mList.find {
                            it is ManagerContent && it.title == "运单"
                        } as ManagerContent).count = count

                        mAdapter.notifyDataSetChanged()
                    }
            }

        // 角色权限
        mLimitStatus
            .observe(this) {
                mList.clear()
                mList.addItems(
                    getViewModel()
                        .getIconList(serviceId, it)
                )

                mAdapter.setDataList(mList)

                getViewModel().getCount("0")
                (it == "1").condition {
                    getViewModel().getCount("1")
                    getViewModel().getShipCount()
                }
            }
    }

    override fun onRestart() {
        super.onRestart()

        getViewModel().getCount("0")
        (mLimitStatus.value == "1")
            .condition {
                getViewModel().getCount("1")
                getViewModel().getShipCount()
            }
    }

    /**
     * 角色权限判断
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .request(
                requestUrl = ReportUrl.getBaseUrl().reportLmt,
                requestMethod = HttpMethod.GET,
                onSuccess = { mLimitStatus.value = it }
            )
    }

}